import { useState } from 'react'
// 引入counterStore
import { useStore } from '../store'
// 引入mobx中间件
import { observer } from 'mobx-react-lite'
import './index.css'

function Task() {
  const [textVal, setTextVal] = useState('')
  const { listStore } = useStore()

  /**
   * 单选回调
   * @param {Event} e 事件
   * @param {number} id
   */
  function checkChange(e, id) {
    listStore.singleCheck(id, e.target.checked)
  }

  /**
   * 全选回调
   * @param {Event} e 事件
   * @param {number} id
   */
   function allCheckChange(e) {
    listStore.checkAll(e.target.checked)
  }

  /**
   * 回车回调函数
   * @param {Event} e 回调事件参数
   */
  function handleKeyDown(e) {
    if(e.keyCode === 13) {
      listStore.addList(textVal)
      setTextVal('')
    }
  }

  return (
    <>
      <div className='task-input'>
        <input type="checkbox" checked={listStore.isAll} onChange={allCheckChange} />
        <input  
          className='input'
          type="text"
          value={textVal}
          placeholder='输入任务，回车新增'
          onChange={(e) => setTextVal(e.target.value)}
          onKeyDown={handleKeyDown}
        />
      </div>
      <div className="task">
        {
          listStore.list.map(item => (
            <div className="task-item" key={item.id}>
              <label>
                <input type="checkbox" checked={item.isDone} onChange={(e) => checkChange(e, item.id)} />{item.title}
              </label>
            </div>
          ))
        }
        <div className="task-item">
          {listStore.completedCount}已完成/{listStore.list.length}总数
        </div>
      </div>
    </>
  )
}

export default observer(Task)
